package cn.com.kh;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * PDF 转 图片
 */
public class PdfToImageUtil {
    private static final Log log = LogFactory.getLog(PdfToImageUtil.class);

    public static List<String> pdf2Pic(String pdfPath, String path, String expand, boolean ismerge) throws Exception {

        File file1 = new File(pdfPath);
        String sourceFileAllName = file1.getName();
        String sourceFileName = sourceFileAllName.substring(0, sourceFileAllName.lastIndexOf("."));

        log.debug("原始文件全名：" + sourceFileAllName);
        log.debug("原始文件名：" + sourceFileName + " 目标路径：" + path + " 目标拓展名：" + expand + " 合并导出：" + ismerge);

        Document document = new Document();
        document.setFile(pdfPath);
        //缩放比例
        float scale = 2.5f;
        //旋转角度
        float rotation = 0f;

        List<String> list = new ArrayList<>();

        List<BufferedImage> piclist = new ArrayList<BufferedImage>();

        // 文件目录检查
        File f = new File(path);
        if (!f.exists()) {
            f.mkdir();
        }

        for (int i = 0; i < document.getNumberOfPages(); i++) {
            BufferedImage image = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX, rotation, scale);

            if (ismerge) {
                image.flush();
                piclist.add(image);

            } else {
                RenderedImage rendImage = image;
                try {
                    String imgName = sourceFileName + "-" + i + "." + expand;
                    String imagePath = path + imgName;
                    File file = new File(imagePath);
                    ImageIO.write(rendImage, expand, file);
                    list.add(imagePath);

                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.flush();
            }
        }
        if (ismerge) {
            String outPath = path + sourceFileName + "-" + "Merge" + "." + expand;
            list.add(yPic(piclist, outPath, expand));
        }
        document.dispose();

        return list;
    }

    /**
     * 将宽度相同的图片，竖向追加在一起 ##注意：宽度必须相同
     *
     * @param piclist 文件流数组
     * @param outPath 输出路径
     */
    public static String yPic(List<BufferedImage> piclist, String outPath, String expand) {// 纵向处理图片
        if (piclist == null || piclist.size() <= 0) {
            log.warn("图片数组为空!");
            return "";
        }
        try {
            int height = 0, // 总高度
                    width = 0, // 总宽度
                    _height = 0, // 临时的高度 , 或保存偏移高度
                    __height = 0, // 临时的高度，主要保存每个高度
                    picNum = piclist.size();// 图片的数量
            int[] heightArray = new int[picNum]; // 保存每个文件的高度
            BufferedImage buffer = null; // 保存图片流
            List<int[]> imgRGB = new ArrayList<int[]>(); // 保存所有的图片的RGB
            int[] _imgRGB; // 保存一张图片中的RGB数据
            for (int i = 0; i < picNum; i++) {
                buffer = piclist.get(i);
                heightArray[i] = _height = buffer.getHeight();// 图片高度
                if (i == 0) {
                    width = buffer.getWidth();// 图片宽度
                }
                height += _height; // 获取总高度
                _imgRGB = new int[width * _height];// 从图片中读取RGB
                _imgRGB = buffer.getRGB(0, 0, width, _height, _imgRGB, 0, width);
                imgRGB.add(_imgRGB);
            }
            _height = 0; // 设置偏移高度为0
            // 生成新图片
            BufferedImage imageResult = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
            for (int i = 0; i < picNum; i++) {
                __height = heightArray[i];
                if (i != 0)
                    _height += __height; // 计算偏移高度
                imageResult.setRGB(0, _height, width, __height, imgRGB.get(i), 0, width); // 写入流中
            }
            File outFile = new File(outPath);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(imageResult, expand, out);// 写图片
            byte[] b = out.toByteArray();
            FileOutputStream output = new FileOutputStream(outFile);
            output.write(b);
            out.close();
            output.close();

            return outPath;

        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void main(String[] args) throws Exception {
        String filePath = "C:\\Users\\lijun\\Documents\\WXWork\\1688850063816002\\Cache\\File\\2021-11\\平安期货企微交互业务.pdf";
        System.out.println(pdf2Pic(filePath, "D:\\PDFDev\\", "jpg", true));
    }
}